package org.geekbang.thinking.in.spring.ioc.dependency.injection;

import org.geekbang.thinking.in.spring.ioc.dependency.injection.annotation.UserGroup;
import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collection;

/**
 * {@link org.springframework.beans.factory.annotation.Qualifier} 注解的依赖注入
 */
public class QualifierAnnotationDependencyInjectionDemo {

    @Autowired
    private User user;

    @Autowired
    @Qualifier("user")
    private User namedUser;

    //整体应用上下文存在4个 User 类型的 Bean
    //superUser
    //user
    //user1
    //user2

    @Autowired
    private Collection<User> allUsers;

    @Autowired
    @Qualifier
    private Collection<User> qualifiedUsers; // user1+user2+user3+user4

    @Autowired
    @UserGroup
    private Collection<User> groupedUsers;//user3+user4

    @Bean
    @Qualifier // 可以进行逻辑分组，后面获取qualifiedUsers时只获取这两个bean
    public User user1(){
        User user = new User();
        user.setId(7L);
        return user;
    }

    @Bean
    @Qualifier // 可以进行逻辑分组
    public User user2(){
        User user = new User();
        user.setId(8L);
        return user;
    }

    @Bean
    @UserGroup
    public User user3(){
        User user = new User();
        user.setId(9L);
        return user;
    }

    @Bean
    @UserGroup
    public User user4(){
        User user = new User();
        user.setId(10L);
        return user;
    }

    public static void main(String[] args) {

        //创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册 Configuration Class (配置类)
        applicationContext.register(QualifierAnnotationDependencyInjectionDemo.class);

        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);

        String xmlResourcePath = "classpath:/META-INF/dependency-lookup-context.xml";
        //加载 XML 资源，解析并生成 BeanDefinition
        beanDefinitionReader.loadBeanDefinitions(xmlResourcePath);

        //启动 Spring 应用上下文(XML配置方式不需要)
        applicationContext.refresh();

        //依赖查找 QualifierAnnotationDependencyInjectionDemo Bean
        QualifierAnnotationDependencyInjectionDemo demo = applicationContext.getBean(QualifierAnnotationDependencyInjectionDemo.class);

        System.out.println(demo.user);
        System.out.println(demo.namedUser);
        System.out.println(demo.allUsers);
        System.out.println(demo.qualifiedUsers);
        System.out.println(demo.groupedUsers);

        //显式的关闭 Spring 应用上下文
        applicationContext.close();
    }
}
